import pandas as pd
import csv
import os
from IPython import embed
from git import Repo
from mailing import send_mail_cse_smtp
from collections import defaultdict
from sys import argv
import traceback
import logging


def gen_link_mail(sid):
    sid = str(sid)
    if len(sid) != 10:
        raise RuntimeError("Wrong SID {}".format(sid))
    return sid + "@link.cuhk.edu.hk"


n_students = 5  # how many students in one team
phase = "Demo mark"

subject = "CSCI3100 Project Demo Marking"

text = """Dear Group {},

Below is the mark of your CSCI3100 project demo.

Project Name: {}

Mark: {} ({})

Comment: {}

The following is the mark distribution:

Maximum: 99.2
Minimum: 77.5
Average: 88.6


We are pleased to see that most groups' projects are quite comprehensive and working smoothly.
Please remember to submit your final report.

Regards,
CSCI3100 TA Group"""


if __name__ == "__main__":
    group_info = pd.read_csv("./final-group.csv")
    mark_info = pd.read_excel(
        "./marks/demo/CSCI3100 (2020R2) Project Demo Marking.xlsx"
    )

    group_addr_dict = defaultdict(list)
    for idx, row in group_info.iterrows():
        for i in range(1, n_students + 1):
            sid = row["SID{}".format(i)]
            if not pd.isnull(sid):
                sid = str(int(row["SID{}".format(i)]))
                group_addr_dict[row["Group ID"]].append(gen_link_mail(sid))

    records = []
    for gid in group_addr_dict:
        print("Sending to {}".format(gid))
        receiver_list = group_addr_dict[gid]
        receiver_list.append("csci3100@cse.cuhk.edu.hk")
        # receiver_list = ["jyliu@cse.cuhk.edu.hk"]

        row = mark_info[mark_info["Group ID"] == gid]

        project_name = row["Project Name"].values[0]
        mark = row["Overall Mark"].values[0]
        grade = row["Grade"].values[0]
        comment = row["Overall Comments"].values[0]

        msg = text.format(
            gid,  # group id
            project_name,
            mark,
            grade,
            comment,
        )

        # print(msg)

        records.append(
            {
                "GroupID": gid,
                "Msg": msg,
            }
        )

        # # uncomment it to send emails
        send_mail_cse_smtp(
            "csci3100",  # cse username
            subject,  # subject
            msg,  # content
            None,  # no attachment
            receiver_list,  # receiver list
        )

        print("Sent to \n {}".format(receiver_list))
        print("-" * 20)

    pd.DataFrame(records).to_csv("{}_records.csv".format(phase), index=False)
    print("Done for {} teams.".format(len(records)))
